package com.nowcoder.community.util;

import com.nowcoder.community.entity.User;
import org.springframework.stereotype.Component;

/**
 * @Author Cl
 * @Date 2024-2024/4/28  13:25
 * @Description 封装ThreadLocal替代session,
 *       1.可避免在用session对象传参,随用随取
 *       2.session会随着登录用户的增多服务端内存占用变大 , ThreadLocal可以即时释放内存,保存用户信息的个数最大上限也就是线程的个数
 */
@Component
public class HostHolder {
    private ThreadLocal<User> users = new ThreadLocal<>();

    public void setUser(User user){
        users.set(user);
    }

    public User getUser(){
        return users.get();
    }

    public void clear(){ // 记得即时释放内存,避免内存泄漏
        users.remove();
    }
}
